package com.bsh.serviceImpl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.bsh.repository.DaoAccountNotice;
import com.bsh.repository.DaoSysConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.api.Exception.ApiException;
import com.bsh.mybatis.dataView.UserAccountInfo;
import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.Share;
import com.bsh.mybatis.model.User;
import com.bsh.service.AccountService;
import com.bsh.service.ApiCloudService;
import com.bsh.service.CloudGoodsService;
import com.bsh.service.CloudUserGoodsService;
import com.bsh.service.ShareService;
import com.bsh.service.UserService;
import com.bsh.utils.ApiMessage;
import com.bsh.utils.Constants;
import com.bsh.utils.Des3;
import com.bsh.utils.DesUtils;
import com.bsh.utils.PrimaryGenerater;

@Service
@Transactional
public class ApiCloudServiceImpl implements ApiCloudService {

	@Autowired
	AccountService accountServ;
	@Autowired
	UserService servUser;
	@Autowired
	ShareService shareService;
	@Autowired
	CloudGoodsService cloudGoodsService;
	@Autowired
	CloudUserGoodsService cloudUserGoodsService;
//	@Autowired
//	DaoSysConfig sysDao;
	@Autowired
	DaoAccountNotice accountNoticeDao;

	@Override
	public ApiMessage sendCloudMoney(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		if (ApiUtils.objIsEmpty(dto.getString("toMobile"))) {
			throw new ApiException("103", "缺少对方手机号");
		}
		if (ApiUtils.objIsEmpty(dto.getBigDecimal("cloudMoney"))) {
			throw new ApiException("103", "缺少赠送商币");
		}else if(dto.getBigDecimal("cloudMoney").compareTo(BigDecimal.ZERO)<=0){
			throw new ApiException("103", "赠送商币金额必须大于0");
		}
		if (ApiUtils.objIsEmpty(dto.getString("payPassword"))) {
			throw new ApiException("103", "缺少支付密码");
		}
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Account accInfo = accountServ.getAccountByUserId(user.getId());
		if (ApiUtils.objIsEmpty(accInfo)) {
			throw new ApiException("102", "账户不存在");
		}

		DesUtils des = new DesUtils();
		if (!accInfo.getPayPassword().equals(des.encryptPassword(dto.getString("payPassword")))) {
			throw new ApiException("102", "支付密码错误");
		}
		User toUser = servUser.getUserByMobile(dto.getString("toMobile"));
		if (ApiUtils.objIsEmpty(toUser)) {
			throw new ApiException("102", "对方用户不存在");
		}
		Account toAccount = accountServ.getAccountByUserId(toUser.getId());
		if (ApiUtils.objIsEmpty(toAccount)) {
			throw new ApiException("102", "对方账户不存在");
		}
		if (accInfo.getCloudMoney().compareTo(dto.getBigDecimal("cloudMoney")) == -1) {
			throw new ApiException("102", "商币余额不足");
		}
		if (toAccount.getId().equals(accInfo.getId())) {
			throw new ApiException("102", "商币不能赠送给自己");
		}

		// 赠送商币
		String sn = PrimaryGenerater.getInstance().next();
		String ip = ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip");
		int res = cloudUserGoodsService.sendCloudMoney(accInfo.getId(), user.getId(), toAccount.getId(), toUser.getId(),
				sn, ip, new BigDecimal(dto.getInteger("cloudMoney")), dto.getString("memo"));
		if (res > 0) {
			msg = new ApiMessage("200", "商币赠送成功");
		} else {
			msg = new ApiMessage("400", "商币赠送失败");
		}
		// msg=new ApiMessage("401","此功能已并入【购买商币】");
		return msg;
	}

	@Override
	public ApiMessage addCloudMoney(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		if (ApiUtils.objIsEmpty(dto.getShort("stype"))) {
			throw new ApiException("105", "缺少分享类型");
		} else if (dto.getShort("stype") < 1 || dto.getShort("stype") > 6) {
			throw new ApiException("102", "分享类型不合法");
		}

		// 先查询出账户
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户或密码错误");
		}
		UserAccountInfo uai = accountServ.getUserAccountInfo(user.getId());
		if (ApiUtils.objIsEmpty(uai)) {
			throw new ApiException("102", "用户账户不存在");
		}

		int cloudMoney = 0;
		// 根据不同的类型对应不同的
		if (dto.getShort("stype") == 1) {
			cloudMoney = Constants.shareCloudMoney.wxpyq;
		} else if (dto.getShort("stype") == 2) {
			cloudMoney = Constants.shareCloudMoney.wxhy;
		} else if (dto.getShort("stype") == 3) {
			cloudMoney = Constants.shareCloudMoney.xlwb;
		} else if (dto.getShort("stype") == 4) {
			cloudMoney = Constants.shareCloudMoney.qqhy;
		} else if (dto.getShort("stype") == 5) {
			cloudMoney = Constants.shareCloudMoney.qqkj;
		} else if (dto.getShort("stype") == 6) {
			cloudMoney = Constants.shareCloudMoney.ewmfx;
		}

		// 统计今日
		Share share = new Share();
		share.setUserid(user.getId());
		Integer sumToday = shareService.sumTodayCloudMoney(share);
		// 如果今日统计商币数+当前添加商币数大于每天限额
		//Integer maxShareCloud = sysDao.getMaxShareCloud();
		
		//Integer maxShareCloud = sysDao.findSysKey("max_share_cloud");

//		if (ApiUtils.objIsNotEmpty(maxShareCloud) && (cloudMoney + sumToday) > maxShareCloud) {
//			throw new ApiException("400", "超过当天添加商币限额，添加商币失败");
//		} else {
//			share.setStype(dto.getShort("stype"));
//			share.setCloudMney(cloudMoney);
//			share.setCreateTime(new Date());
//			Integer res = shareService.saveShare(share);
//			String sn = PrimaryGenerater.getInstance().next();
//			String ip = ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip");
//			// ip限制
//			Integer shareTimes = accountNoticeDao.getIpDayShareCloudTimes(ip);
//			//Integer limitTimes = sysDao.getDayIpShareLimit();
//			Integer limitTimes = sysDao.findSysKey("day_ip_share_cloud_limit");
//
//
//
//			if (ApiUtils.objIsNotEmpty(ip) && ApiUtils.objIsNotEmpty(shareTimes) && ApiUtils.objIsNotEmpty(limitTimes)
//					&& shareTimes + 1 > limitTimes) {
//				throw new ApiException("400", "超过当天分享次数，添加商币失败");
//			}
//
//			// 添加商币
//			res = shareService.shareAddCloudMoney(uai.getAccountId(), user.getId(), sn, ip, new BigDecimal(cloudMoney));
//			if (res > 0) {
//				msg = new ApiMessage("200", "添加商币成功");
//			} else {
//				msg = new ApiMessage("400", "添加商币失败");
//			}

	//	}

		return msg;
	}

	@Override
	public ApiMessage buyCloudMoney(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);

		if (ApiUtils.objIsEmpty(dto.getString("payPassword"))) {
			throw new ApiException("103", "缺少支付密码");
		}
		// 用户
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		// 先查询出账户
		Account accInfo = accountServ.getAccountByUserId(user.getId());
		if (ApiUtils.objIsEmpty(accInfo)) {
			throw new ApiException("102", "用户账户不存在");
		}
		DesUtils des = new DesUtils();
		if (!accInfo.getPayPassword().equals(des.encryptPassword(dto.getString("payPassword")))) {
			throw new ApiException("102", "支付密码错误");
		}

		if (ApiUtils.objIsEmpty(dto.getBigDecimal("money"))) {
			throw new ApiException("103", "缺少购买数量");
		} else if (ApiUtils.objIsEmpty(dto.getBigDecimal("selfCloudMoney"))) {
			throw new ApiException("103", "缺少商币值");
		} else if (ApiUtils.objIsEmpty(dto.getBigDecimal("otherCloudMoney"))) {
			throw new ApiException("103", "缺少给对方商币值");
		} else if (ApiUtils.objIsEmpty(dto.getBigDecimal("otherMobile"))) {
			throw new ApiException("103", "请输入会员账号");
		} else if (dto.getBigDecimal("money").compareTo(accInfo.getMoney()) == 1) {
			throw new ApiException("103", "账户余额不足，请充值");
		} else if (dto.getBigDecimal("money").compareTo(new BigDecimal(1000000)) == 1) {
			throw new ApiException("103", "超过充值最大限额100万");
		}
		if (ApiUtils.objIsEmpty(dto.getBigDecimal("selfCloudMoney"))) {
			throw new ApiException("103", "缺少兑换商币数");
		}

		// 检查接收方会员 是否存在
		User toUser = servUser.getUserByMobile(dto.getString("otherMobile"));
		if (ApiUtils.objIsEmpty(toUser)) {
			throw new ApiException("102", "会员" + dto.getString("otherMobile") + "不存在");
		}
		Account toAccInfo = accountServ.getAccountByUserId(toUser.getId());
		if (ApiUtils.objIsEmpty(toAccInfo)) {
			throw new ApiException("102", "会员账户不存在");
		}
		// 检查金额与商币的比例值 是否正确
		if (dto.getBigDecimal("money").compareTo(dto.getBigDecimal("selfCloudMoney")) != 0) {
			throw new ApiException("102", "金额与商币不相同");
		} else if (dto.getBigDecimal("otherCloudMoney").compareTo(dto.getBigDecimal("money")
				.multiply(new BigDecimal(100)).divide(new BigDecimal(15), 2, BigDecimal.ROUND_HALF_UP)) != 0) {
			throw new ApiException("102", "金额与接收商币比例不对");
		}

		// 添加商币
		String sn = PrimaryGenerater.getInstance().next();
		String ip = ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip");
		int res = cloudUserGoodsService.buyCloudMoney(accInfo.getId(), user.getId(), toAccInfo.getId(), toUser.getId(),
				sn, ip, dto.getBigDecimal("money"), dto.getBigDecimal("selfCloudMoney"),
				dto.getBigDecimal("otherCloudMoney"));
		if (res > 0) {
			msg = new ApiMessage("200", "购买商币成功");
		} else {
			msg = new ApiMessage("400", "购买商币失败");
		}
		return msg;
	}

	@Override
	public ApiMessage isBuyCloudMoney(JSONObject dto) throws ApiException {
		ApiMessage msg = new ApiMessage();
		ApiUtils.checkUserNameToken(dto);
		// 用户
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		// 2016/9/14
		// if(user.getIsMerchant()==1||user.getLevel().equals("gold")){
		if (ApiUtils.objIsNotEmpty(user.getIsMerchant()) && user.getIsMerchant() == 1) {
			msg.setCode("200");
			msg.setMessage("可以购买商币");
		} else {
			// throw new ApiException("102", "只有金钻或者商家可以购买");
			throw new ApiException("102", "只有商家可以购买");
		}
		return msg;
	}

	@Override
	public ApiMessage isCloudToShares(JSONObject dto) throws ApiException {
		ApiMessage msg = new ApiMessage();
		ApiUtils.checkUserNameToken(dto);
		// 用户
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		// 金钻或合伙人
		if ("gold".equals(user.getLevel()) || user.getPartnerLevel() > 0) {
			msg.setCode("200");
			msg.setMessage("可以兑换期权");
		} else {
			throw new ApiException("102", "无兑换权限");
		}
		return msg;
	}

	@Override
	public ApiMessage cloudToShares(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);

		if (ApiUtils.objIsEmpty(dto.getString("payPassword"))) {
			throw new ApiException("103", "缺少支付密码");
		}
		// 用户
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		// 先查询出账户
		Account accInfo = accountServ.getAccountByUserId(user.getId());
		if (ApiUtils.objIsEmpty(accInfo)) {
			throw new ApiException("102", "用户账户不存在");
		}
		DesUtils des = new DesUtils();
		if (!accInfo.getPayPassword().equals(des.encryptPassword(dto.getString("payPassword")))) {
			throw new ApiException("102", "支付密码错误");
		}

		if (ApiUtils.objIsEmpty(dto.getBigDecimal("changeCloudShares"))) {
			throw new ApiException("103", "缺少兑换期权数");
		} else if (dto.getBigDecimal("changeCloudShares").compareTo(BigDecimal.ZERO) <= 0
				|| dto.getInteger("changeCloudShares") % 100 != 0) {
			throw new ApiException("103", "期权数必须是100的正整数倍");
		} 
		
		
		// 获取兑换比例
		BigDecimal rate = BigDecimal.ONE;
		Integer limitShares=0;
//		if (ApiUtils.objIsEmpty(user.getPartnerLevel())||user.getPartnerLevel()==0) {
//			rate = new BigDecimal(sysDao.findSysKey("un_partner_cloudshares_rate"));
//			limitShares=sysDao.findSysKey("gold_limit_shares");
//		} else {
//			rate = new BigDecimal(sysDao.findSysKey("partner_cloudshares_rate"));
//			limitShares=sysDao.findSysKey("partner_limit_shares_level"+user.getPartnerLevel().toString());
//		}
		// 计算所需商币数   商币=期权*商币/期权
		BigDecimal changeCloudMoney = dto.getBigDecimal("changeCloudShares").multiply(rate);
		if(changeCloudMoney.compareTo(accInfo.getCloudMoney())>0){
			throw new ApiException("103", "商币余额不足");
		}
		
		if(accInfo.getCloudShares().add(dto.getBigDecimal("changeCloudShares")).compareTo(new BigDecimal(limitShares))>0){
			throw new ApiException("103", "期权超过最大限额");
		}
		
		// 添加期权
		String sn = PrimaryGenerater.getInstance().next();
		String ip = ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip");
		int res = cloudUserGoodsService.changeCloudMoneyToShare(accInfo.getId(), user.getId(),sn, ip, changeCloudMoney,dto.getBigDecimal("changeCloudShares"));
		if (res > 0) {
			msg = new ApiMessage("200", "商币兑换成功");
			accInfo = accountServ.getAccountByUserId(user.getId());
			Map<String, Object> data=new HashMap<String, Object> ();
			data.put("cloudShares", accInfo.getCloudShares());
			msg.setData(Des3.encResponse(data));
		} else {
			msg = new ApiMessage("400", "商币兑换失败");
		}
		return msg;
	}

}
